package xin.fallen.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Collection;

/**
 * Created by itsxu on 2016/8/5.
 */
public class MyBatisUtil {
	private static SqlSessionFactory factory = null;

	public static SqlSession getSqlSession() {
		SqlSession sqlSession = null;
		if (factory != null) {
			sqlSession = factory.openSession();
			return sqlSession;
		}

		File SqlmapConfigPath=searchFile("SqlMapperConfig.xml");
		try {
			Reader reader = new FileReader(SqlmapConfigPath);
			factory = new SqlSessionFactoryBuilder().build(reader);
			sqlSession = factory.openSession();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sqlSession;
	}

	public static File searchFile(String filename) {
		File res = null;
		try {
			//扩展名
			String extName = FilenameUtils.getExtension(filename);
			//递归查找
			Collection<File> list = null;
			list = FileUtils.listFiles(new File(new File(Thread.currentThread().getContextClassLoader().getResource("").getPath()).getParent()), new String[]{extName.toLowerCase(), extName.toUpperCase()}, true);
			//确定文件
			for (File file : list) {
				if (file.getName().equalsIgnoreCase(filename)) {
					res = file;
					break;
				}
			}
		} catch (Exception e) {
		}
		return res;
	}

}
